/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socket.chat;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author atsi
 */
public class ChatServer {

    public static ArrayList<Socket> ConnectionArrayList = new ArrayList<Socket>();
    public static ArrayList<String> ConnectedUsers = new ArrayList<String>();
    private boolean running = true;
    private ChatServerReturn chat;
    private Socket socket;

    public static void main(String[] args) {
        ChatServer cs = new ChatServer();
        cs.init();
    }

    public void init() {
        try {
            final int port = 444;
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("CHAT-Waiting for Clients.....");

            while (running) {
                socket = serverSocket.accept();
                ConnectionArrayList.add(socket);

                System.out.println("CHAT-Client Connected from :" + socket.getLocalAddress().getHostName());

                AddUserName(socket);

                chat = new ChatServerReturn(socket);
                Thread chatThread = new Thread(chat);
                chatThread.start();
            }

        } catch (IOException ex) {
            Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void AddUserName(Socket s) {
        try {
            Scanner input = new Scanner(s.getInputStream());
            String UserName = input.nextLine();
            ConnectedUsers.add(UserName);

            for (int i = 1; i <= ChatServer.ConnectionArrayList.size(); i++) {

                Socket temp_socket = (Socket) ChatServer.ConnectionArrayList.get(i - 1);
                PrintWriter out = new PrintWriter(temp_socket.getOutputStream());
                out.println("#?!" + ConnectedUsers);
                out.flush();

            }

        } catch (IOException ex) {
            Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }


    }
    
    public void stop(){
        try {
            chat.setRunning(false);
            socket.close();
            running = false;
        } catch (IOException ex) {
            Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
